package com.heima.wemedia.service.impl;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public WmMaterial uploadPicture(MultipartFile multipartFile) {
        //校验参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            //参数不存在异常
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //开始文件上传
        //从multipartFile获得图片对象
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));//获得文件的格式
        //组装文件名用uuid声明文件名并将"-"替换为空
        String fileName = UUID.randomUUID().toString().replace("-", "");
        fileName = fileName + postfix;
        String imgFile = null;
        try {
            imgFile = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());//String prefix, String filename,InputStream inputStream
        } catch (IOException e) {
            e.printStackTrace();//文章上传失效
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }
        //成功上组装对象存入数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(imgFile);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        save(wmMaterial);
        return wmMaterial;
    }

    /**
     * 素材链表查询
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult listWmMaterial(WmMaterialDto wmMaterialDto) {
        //参数校验
        wmMaterialDto.checkParam();//不为空原有的数据,为空默认page=1,size=10
        //没有传的查询所有
        //查询条件
        LambdaQueryWrapper<WmMaterial> lqwWM = new LambdaQueryWrapper<>();
        lqwWM.eq(wmMaterialDto.getIsCollection() != null, WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        IPage<WmMaterial> page = new Page<>();
        page.setPages(wmMaterialDto.getPage());
        page.setSize(wmMaterialDto.getSize());
        page(page, lqwWM);
        ResponseResult pageResponseResult = new PageResponseResult(wmMaterialDto.getPage(), (int) page.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteWmMaterialById(Integer id) {
        //参数校验
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //查询素材表和文章表如果文章引用了则不能删除,反之删除文章只需取消关联就可以了
        LambdaQueryWrapper<WmNewsMaterial> lqw = new LambdaQueryWrapper<>();
        lqw.eq(WmNewsMaterial::getMaterialId, id);
        List<WmNewsMaterial> wmNewsMaterialList = wmNewsMaterialMapper.selectList(lqw);
        if (wmNewsMaterialList != null && wmNewsMaterialList.size() > 0) {
            //被关联就不能删除
            return ResponseResult.errorResult(AppHttpCodeEnum.NOT_DELETE_FILE);
        }
        //没有关联删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectAndCollect(Integer id, Short collect) {
        //校验参数
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        //查询数据库id是否存在
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //修改收藏
        wmMaterial.setIsCollection(collect);
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
